#include"SeqList.h"

//顺序表的初始化
void SeqListInit(SeqList *ps)
{
	assert(ps);

	ps->a=NULL;
	ps->size = ps->capacity = 0;
}

//顺序表的销毁
void SeqListDestroy(SeqList *ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;
	ps->size = ps->capacity = 0;
}

//判断容量是否已满
void SeqCheckCapacity(SeqList* ps)
{
	if (ps->size == ps->capacity)        
	{
		int newcapacity;
		if (ps->capacity == 0)                     //判断原来的容量是否为空
		{
			newcapacity = 4;
		}
		else
		{
			newcapacity = ps->capacity * 2;
		}
		SeqDataType* newA = realloc(ps->a, sizeof(SeqDataType) * newcapacity);
		if (newA == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}
		ps->a = newA;
		ps->capacity = newcapacity;
	}
}

//顺序表的头插
void SeqListPushBack(SeqList *ps, SeqDataType x)
{
	assert(ps);

	SeqCheckCapacity(ps);

	ps->a[ps->size] = x;
	ps->size++;
 }

//顺序表的尾插
void SeqListPushFront(SeqList *ps, SeqDataType x)
{
	assert(ps);

	SeqCheckCapacity(ps);

	int end = ps->size - 1;
	while (end >= 0)
	{
		ps->a[end + 1] = ps->a[end];
		--end;
	}
	ps->a[0] = x;
	ps->size++;
}

//顺序表的头删
void SeqListPopFront(SeqList* ps)
{
	assert(ps);
	assert(ps->size > 0);

	for (int i = 0; i < ps->size - 1; ++i)
	{
		ps->a[i] = ps->a[i + 1];
	}
	--ps->size;
}

//顺序表的尾删
void SeqListPopBack(SeqList* ps)
{
	assert(ps);
	assert(ps->size > 0);

	--ps->size;
}

//顺序表的打印
void SeqListPrint(SeqList* ps)
{
	assert(ps);

	for (int i = 0; i < ps->size; ++i)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}

//顺序表的查找
int SeqListFind(SeqList* ps, SeqDataType x)
{
	assert(ps);

	for (int i = 0; i < ps->size; ++i)
	{
		if (ps->a[i] == x)
		{
			return i;
		}
	}
	return -1;
}

//顺序表的插入
void SeqListInsert(SeqList* ps, int pos, SeqDataType x)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	
	SeqCheckCapacity(ps);

	int end = ps->size - 1;
	while (end >= pos)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[pos] = x;
	++ps->size;
}

//顺序表的删除
void SeqListErase(SeqList* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);

	int i = pos;
	while (i < ps->size - 1)
	{
		ps->a[i] = ps->a[i + 1];
		++i;
	}
	--ps->size;
}